import React, { Component } from 'react'
import { Table, Tag, Modal, Popover, Button } from 'antd';
import axios from 'axios'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined} from '@ant-design/icons';

const { confirm } = Modal;
export default class RoleList extends Component {
  state = {
    dataSource: []
  }
  componentDidMount() {
    this.getRoleList()
  }
  getRoleList = () => {
    axios.get('http://localhost:8000/right?_embed=children').then(res => {
      res.data.forEach(element => {
        if (element.children?.length == 0) {
          element.children = ""
        }
      });
      this.setState({
        dataSource: res.data
      })
    })
  }
  showConfirm(item) {
    let _this = this
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      onOk() {
        _this.detaMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // 删除 当前页面同步状态 + 后端同步
  detaMethod(item) {

    let newdata = []
    if (item.grade === 1) {
      newdata = this.state.dataSource.filter(data => data.id !== item.id)
      axios.delete(`http://localhost:8000/right/${item.id}`).then(res => {
        console.log(res)
      })
    } else {
      console.log(item.rightId)
      // 查询父级
      let list = this.state.dataSource.filter(data => data.id === item.rightId)
      console.log("查询父级", list)
      // 去除父级下的匹配项
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      console.log("去除父级下的匹配项", list)
      newdata = this.state.dataSource
      axios.delete(`http://localhost:8000/children/${item.id}`).then(res => {
        console.log(res)
      })
    }

    this.setState({
      dataSource: [...newdata]
    })
  }
  render() {
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '权限名称',
        dataIndex: 'title',
      },
      {
        title: '权限路径',
        dataIndex: 'key',
        render: (key) => {
          return <Tag color="orange">{key}</Tag>
        }
      },
      {
        title: '操作',
        render: (key) => {
          return <div>
            <Button type="danger" shape="circle" onClick={() => { this.showConfirm(key) }} icon={<DeleteOutlined />} />
            <Popover content={<div>123</div>} title="Title" trigger="click">
              <Button type="primary" shape="circle" icon={<EditOutlined />} />
            </Popover>
          </div>
        }
      },
    ];
    return (
      <div>
        <Table dataSource={this.state.dataSource} columns={columns} pagination={
          { pageSize: 5 }
        } />;
      </div>
    )
  }
}
